package com.alibaba.gao.config;

import com.alibaba.gao.delayQueue.Separator;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.ReadMode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * Title:配置类
 * </p>
 * <p>
 * Description:redisson延迟队列配置，采用哨兵模式
 * </p>
 * <p>
 * Copyright: 2020~2021
 * </p>
 * <p>
 * Company/Department: EnnCloud
 * </p>
 *
 * @author zhangyiwu <b>Creation Time:</b> 2021-11-22 14:44:39
 * @since V1.0
 */
@Configuration
public class RedissonDelayConfig {

    @Value("${spring.redis.sentinel.nodes}")
    private String sentinelNodes;

    @Value("${spring.redis.sentinel.master}")
    private String sentinelMaster;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.database}")
    private int database;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        String[] nodes = sentinelNodes.split(Separator.COMMA);
        List<String> newNodes = new ArrayList<>(nodes.length);
        newNodes.addAll(Arrays.asList(nodes));
        newNodes = newNodes.stream().map(item -> Separator.REDIS_PREFIX + item).collect(Collectors.toList());
        config.useSentinelServers().addSentinelAddress(newNodes.toArray(new String[0])).setMasterName(sentinelMaster)
            .setReadMode(ReadMode.SLAVE).setPassword(password).setDatabase(database)
            .setMasterConnectionMinimumIdleSize(10).setSlaveConnectionMinimumIdleSize(10).setTimeout(timeout);
        return Redisson.create(config);
    }
}
